package com.snowflake.ecatalog.web.profile;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.snowflake.ecatalog.contant.CompanyLaunchType;
import com.snowflake.ecatalog.entity.Company;
import com.snowflake.ecatalog.entity.CompanyLaunch;
import com.snowflake.ecatalog.entity.ResourceInfo;
import com.snowflake.ecatalog.service.profile.CompanyLaunchService;
import com.snowflake.ecatalog.util.FileOperateUtil;
import com.snowflake.ecatalog.util.LoginUtil;

/**
 * 广告图片管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /startup/ Create page : GET /startup/create Create action :
 * POST /startup/create Update page : GET /startup/update/{id} Update action :
 * POST /startup/update Delete action : GET /startup/delete/{id}
 * 
 */
@Controller
@RequestMapping(value = "/startup")
public class StartupController {

	private static final int PAGE_SIZE = 10;

	private static final int COMPANY_LAUNCH_TYPE = CompanyLaunchType.STARTUP;

	@Autowired
	private CompanyLaunchService service;

	@RequestMapping(value = "")
	public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model,
			ServletRequest request, HttpSession session) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Long profileId = LoginUtil.getProfileIdFromSession(session);
		Page<CompanyLaunch> launchs = service.getCompanyLaunchs(profileId, COMPANY_LAUNCH_TYPE, searchParams,
				pageNumber, PAGE_SIZE);
		model.addAttribute("launchs", launchs);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return "profile/startupList";
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("startup", new Company());
		model.addAttribute("action", "create");
		return "profile/startupForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid CompanyLaunch newStartup, RedirectAttributes redirectAttributes, ServletRequest request)
			throws Exception {
		newStartup.setType(COMPANY_LAUNCH_TYPE);
		newStartup.setProfile(LoginUtil.getProfileFromRequest(request));
		List<ResourceInfo> resourceInfoList = FileOperateUtil.upload((HttpServletRequest) request,
				String.valueOf(LoginUtil.getProfileIdFromRequest(request)));
		service.saveCompanyLaunch(newStartup, resourceInfoList);
		redirectAttributes.addFlashAttribute("message", "创建广告图片成功");
		return "redirect:/startup/";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		model.addAttribute("startup", service.getCompanyLaunch(id));
		model.addAttribute("action", "update");
		return "profile/startupForm";
	}

	@RequestMapping(value = "getImgPath", method = RequestMethod.POST)
	public @ResponseBody
	Map<Integer, ResourceInfo> getImgPath(@RequestParam("id") Long id) {
		return service.getImgPathMap(id);
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadStartup") CompanyLaunch startup,
			RedirectAttributes redirectAttributes, ServletRequest request) throws Exception {
		Long profileId = LoginUtil.getProfileIdFromRequest(request);
		List<ResourceInfo> resourceInfoList = FileOperateUtil.upload((HttpServletRequest) request,
				String.valueOf(profileId));
		service.updateCompanyLaunch(startup, resourceInfoList);
		redirectAttributes.addFlashAttribute("message", "更新广告图片成功");
		return "redirect:/startup/";
	}

	@RequestMapping(value = "enable/{id}")
	public String enable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes, HttpSession session) {
		Long profileId = LoginUtil.getProfileIdFromSession(session);
		long enableStartupCount = service.getEnableCompanyLauchCount(profileId, CompanyLaunchType.STARTUP);
		if (enableStartupCount < 2) {
			if (service.checkEnableCompanyLauch(id, CompanyLaunchType.STARTUP)) {
				service.enableCompanyLauch(id);
				redirectAttributes.addFlashAttribute("message", "启用广告图片成功");
			} else {
				redirectAttributes.addFlashAttribute("message", "广告图片未上传完整，启用广告图片失败");
			}
		} else {
			redirectAttributes.addFlashAttribute("message", "广告图片最多启用2张,启用广告图片失败");
		}
		return "redirect:/startup/";
	}

	@RequestMapping(value = "disable/{id}")
	public String disable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes, HttpSession session) {
		service.disableCompanyLauch(id);
		redirectAttributes.addFlashAttribute("message", "禁用广告图片成功");
		return "redirect:/startup/";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		service.deleteCompanyLaunch(id);
		redirectAttributes.addFlashAttribute("message", "删除广告图片成功");
		return "redirect:/startup/";
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出CompanyLaunch对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadStartup")
	public CompanyLaunch getCompanyLaunch(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return service.getCompanyLaunch(id);
		}
		return null;
	}
}
